﻿using AutoMapper;
using BS.Infra;
using BS.Infra.Interface;
using MediatR;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;

namespace BS.Read.Api.Handler.RBAC
{
    public class GetRBACPermissionsTreeHandler : IRequestHandler<GetPermissionsRequestDTO, ApiResult>
    {
        private readonly IPermissionsRepository _permissionsRepository;

        private readonly IMapper _mapper;

        private readonly ILogger<GetRBACPermissionsTreeHandler> _logger;

        private readonly IHttpContextAccessor _httpContextAccessor;

        private readonly IUserRoleRepository _userRoleRepository;

        private readonly IRolePermissionsRepository _rolePermissionRepository;
        public GetRBACPermissionsTreeHandler(IPermissionsRepository permissionsRepository, IMapper mapper, ILogger<GetRBACPermissionsTreeHandler> logger, IHttpContextAccessor httpContextAccessor, IUserRoleRepository userRoleRepository, IRolePermissionsRepository rolePermissionRepository)
        {
            _permissionsRepository = permissionsRepository;
            _mapper = mapper;
            _logger = logger;
            _httpContextAccessor = httpContextAccessor;
            _userRoleRepository = userRoleRepository;
            _rolePermissionRepository = rolePermissionRepository;
        }
        public async Task<ApiResult> Handle(GetPermissionsRequestDTO request, CancellationToken cancellationToken)
        {
            var list=await GetPermissionsTree();
            //var user = _httpContextAccessor.HttpContext?.User.FindFirstValue("Sub");
            //var userId =Convert.ToInt32(_httpContextAccessor.HttpContext?.User.FindFirstValue("Jti"));
            //var HttpContext = _httpContextAccessor.HttpContext;
            //// 从请求头中获取 token
            //var token = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer", "");
            ////当前用户对应的权限ID
            //var userRoles = await _userRoleRepository.GetAllAsync(x => x.UserId == userId);
            //var roleIds = userRoles.Select(x => x.RoleId).ToArray();
            //var userPermissions = await _rolePermissionRepository.GetAllAsync(x => roleIds.Contains(x.RoleId));
            //var PermissionIds = userPermissions.Select(x => x.PermissionId).ToArray();
            ////过滤出当前用户的权限
            //list = list.Where(x => PermissionIds.Contains(x.PermissionId)).ToList();
            return await Task.FromResult(ApiResult.Ok(list));
        }

        public async Task<IList<GetPermissionsReponseDTO>> GetPermissionsTree(int partid = 0)
        {
            try
            {
                var permissions = await _permissionsRepository.GetAllAsync(x => x.PartId == partid);

                var permissionsDto = _mapper.Map<IList<GetPermissionsReponseDTO>>(permissions);

                foreach (var item in permissionsDto)
                {
                    item.Children = await GetPermissionsTree(item.PermissionId);
                }

                return permissionsDto;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "GetPermissionsTree");
                throw;
            }
        }
    }
}
public class GetPermissionsRequestDTO:IRequest<ApiResult>
{

}
public class GetPermissionsReponseDTO
{
    public int PermissionId { get; set; }
    /// <summary>
    /// 权限名称
    /// </summary>
    public string PermissionName { get; set; } = string.Empty;

    /// <summary>
    /// 路由
    /// </summary>
    public string Url { get; set; } = string.Empty;
    /// <summary>
    /// 路由名称
    /// </summary>
    public string RoutingName { get; set; } = string.Empty;
    /// <summary>
    /// 组件
    /// </summary>
    public string Component { get; set; } = string.Empty;
    /// <summary>
    /// 子路由
    /// </summary> 
    public IList<GetPermissionsReponseDTO> Children { get; set; } = new List<GetPermissionsReponseDTO>();
}